import React, { useEffect, useState } from "react";
import { View, Text } from '@tarojs/components'
import TabBar from "../../components/tabbar";
import { getMenuButtonBoundingClientRect,useShareAppMessage } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import { NavBar, TreeSelect, Icon, Tab, Tabs, Image } from '@antmjs/vantui'
import { getCategory } from "../../https/application";
import { GetAppList } from "../../https/home";
import { HOST, diffTime,judgeLogin } from '../../utils/const'
import "./index.scss"

const Application = () => {

    const btn = getMenuButtonBoundingClientRect();
    const res = Taro.getSystemInfoSync();
    const [list, setList] = useState([])
    const [subList, setSubList] = useState([])
    const [platform, setPlatform] = useState('android')
    const [category, setCategory] = useState('1')
    const [mainActiveIndex, setMainActiveIndex] = useState(0)
    const [screenHeight, setScreenHeight] = useState(0)

    const setState = (newState) => {
        changeState({
            ...state,
            ...newState,
        })
    }

    useEffect(() => {
        getAppListData()
        Taro.getSystemInfo({
            success: function (res) {
                console.log(res.windowHeight) // 当前屏幕的可用高度
                setScreenHeight(res.windowHeight)
            }
        })
    }, [])

    useEffect(() => {
        getAPPList()
    }, [category, platform])

    useShareAppMessage((res) => {
        if (res.from === "button") {
          // 来自页面内分享按钮
        } else {
          // 右上角分享好友
        }
    
        return {
          title: "", // 分享卡片的title
          path: "", // 分享卡片的小程序路径
          imageUrl: "", // 分享卡片的图片链接
        };
      });

    const getAPPList = () => {
        GetAppList({ platform, category }).then((res) => {
            if (res.data.length > 0) {
                let data = res.data.filter((item) => item.category == category)
                setSubList(data)
            } else {
                setSubList([])
            }
        })
    }

    const getAppListData = () => {
        Taro.showLoading({ title: "加载中" })
        getCategory().then((res) => {
            Taro.hideLoading()
            if (res.success) {
                if (res.data.length > 0) {
                    let data = []
                    res.data.map((item) => {
                        data.push({ text: item.label, id: item.value })
                    })
                    setList(data)
                } else {
                    setList([])
                }
            }
        })
    }

    const navView = () => {
        return (
            <View className='nav-search' onClick={() => Taro.navigateTo({ url: '/pages/home/components/search_page/index' })}>
                <Icon name='search' size={45} />
                <View className='text'>
                    搜索应用
                </View>
            </View>
        )
    }

    const onClickNav = ({ detail = {} }) => {
        setMainActiveIndex(detail.index || 0,)

        let data = list[detail.index]
        setCategory(data.id)
    }

    const itemView = () => {
        return subList.map((item, index) => {
            return (
                <View key={index} onClick={() => {
                    Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })
                    if(judgeLogin()){
                        let array = [];
                        if (Taro.getStorageSync("footprint")) {
                            array = JSON.parse(Taro.getStorageSync("footprint"));
                            let newArr = array
                                .map((storeItem) => {
                                    if (storeItem.id != item.id) {
                                        return storeItem;
                                    }
                                })
                                .filter((storeItem) => storeItem != undefined);
                            newArr.unshift({ ...item });
                            Taro.setStorage({
                                key: "footprint",
                                data: JSON.stringify(newArr),
                            });
                        } else {
                            let itemData = [
                                {
                                    ...item
                                },
                            ];
                            Taro.setStorage({
                                key: "footprint",
                                data: JSON.stringify(itemData),
                            });
                        }
                    }
                }}
                    style={{
                        display: 'flex', flexDirection: 'row', alignItems: 'center', width: '90%', margin: '0 auto',
                        marginTop: index == 0 ? 0 : 20,
                        paddingBottom: index == subList.length - 1 ? 40 : 0
                    }}>
                    <Image radius={10} width={120} height={120} src={HOST + item?.icon} />
                    <View style={{ display: 'flex', flexDirection: 'column', marginLeft: 20 }}>
                        <View style={{ fontWeight: 'bold', fontSize: 15 }}>{item?.name}</View>
                        <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                            {/* <View className="star-view">
                                <Icon name="star" color="#13b858" size={40} />
                                <Text className="star-text">9.0</Text>
                            </View> */}
                            <View style={{ fontSize: 14, color: '#13b858' }}>{item?.version}</View>
                        </View>
                        <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                            <View style={{ fontSize: 12 }}>{item?.size}</View>
                            <View style={{ fontSize: 12, marginLeft: 10 }}>{item?.create_time ? diffTime(new Date(item?.create_time).getTime()) : '未知'}</View>
                        </View>
                    </View>
                </View>
            )
        })
    }

    return (
        <View className='application-view'>
            <NavBar
                title={navView()}
                fixed
                leftText='应用类别'
            />
            <Tabs sticky={true} active={'android'}
                ellipsis={false}
                offsetTop={btn.bottom + 10}
                lazyRender
                style={{ paddingTop: btn.bottom + 10 }}
                onChange={(val) => {
                    setPlatform(val.detail.name)
                }}
            >
                <Tab title="安卓手机" name="android">
                    <TreeSelect
                        height={`${screenHeight - (btn.bottom + (res.platform=='ios'?144:100))}px`}
                        items={list}
                        mainActiveIndex={list.length > 0 ? mainActiveIndex : null}
                        onClickNav={onClickNav}
                        renderContent={itemView()}
                    />
                </Tab>
                <Tab title="苹果手机" name="ios">
                    <TreeSelect
                        height={`${screenHeight - (btn.bottom + (res.platform=='ios'?144:100))}px`}
                        items={list}
                        mainActiveIndex={list.length > 0 ? mainActiveIndex : null}
                        onClickNav={onClickNav}
                        renderContent={itemView()}
                    />
                </Tab>
                <Tab title="windows" name="windows">
                    <TreeSelect
                        height={`${screenHeight - (btn.bottom + (res.platform=='ios'?144:100))}px`}
                        items={list}
                        mainActiveIndex={list.length > 0 ? mainActiveIndex : null}
                        onClickNav={onClickNav}
                        renderContent={itemView()}
                    />
                </Tab>
                <Tab title="MAC电脑" name="mac">
                    <TreeSelect
                        height={`${screenHeight - (btn.bottom + (res.platform=='ios'?144:100))}px`}
                        items={list}
                        mainActiveIndex={list.length > 0 ? mainActiveIndex : null}
                        onClickNav={onClickNav}
                        renderContent={itemView()}
                    />
                </Tab>
            </Tabs>
            <TabBar active={'application'} />
        </View>
    )
}

export default Application